package servlets.ads;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;
import structures.FeedbackInsertionOutcome;
import twitter4j.internal.org.json.JSONObject;

public class InsertFeedback extends HttpServlet {
	
	private static final long serialVersionUID = -7062844535110325485L;
	private static final String URLBASE = "http://localhost:8080/DatabaseRESTWebService/AddFeedback?";
	private static final String GAMIFYADDPOINTURLBASE = "http://localhost:8080/GamifyRESTWebProject/AddPoint?";
	//private static final String GAMIFYADDPOINTURLBASE = "http://gamificationservice.herokuapp.com/AddPoint?";
	
	protected void doPut(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		String idSeller,answer, idAdvertisement, feedbackText, feedbackValue, inputLine;
		URL url;
		BufferedReader reader;
		StringBuffer responseBuffer;
		JsonManager jsonManager;
		JSONObject answerJson;
		FeedbackInsertionOutcome feedbackInsertionOutcome;
		jsonManager = new JsonManager();
		idSeller = request.getParameter("idSeller");
		idAdvertisement = request.getParameter("idAdvertisement");
		feedbackText = request.getParameter("feedbackText").replace(" ", "%20");
		feedbackValue = request.getParameter("feedbackValue");
		feedbackInsertionOutcome = new FeedbackInsertionOutcome();
		try {
			url = new URL(URLBASE + "idAdvertisement=" + idAdvertisement + "&feedbackText=" + feedbackText + "&feedbackValue=" + feedbackValue);
			HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection.setRequestMethod("PUT");
			httpConnection.setDoOutput(true); 
			httpConnection.setDoInput(true);
			httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			
			reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

			responseBuffer = new StringBuffer();
			
			while ((inputLine = reader.readLine()) != null) {
				responseBuffer.append(inputLine);
			}
			reader.close();

			answer = responseBuffer.toString();

			if(answer.equals("null")){
				feedbackInsertionOutcome.setAdvertisement(null);
				feedbackInsertionOutcome.setError(true);
			}
			else
			{
				feedbackInsertionOutcome.setAdvertisement(jsonManager.toAD(answer));
				feedbackInsertionOutcome.setError(false);
			}
			
			if(feedbackValue.equals("true")){
				url = new URL(GAMIFYADDPOINTURLBASE + "idSeller=" + idSeller + "&idFeedback=" + idAdvertisement);
				httpConnection = (HttpURLConnection) url.openConnection();
				httpConnection.setRequestMethod("GET");
				httpConnection.setDoOutput(true); 
				httpConnection.setDoInput(true);
				httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				
				reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

				responseBuffer = new StringBuffer();
				
				while ((inputLine = reader.readLine()) != null) {
					responseBuffer.append(inputLine);
				}
				reader.close();

				answer = responseBuffer.toString();

				if(answer.equals("null")){
					feedbackInsertionOutcome.setGamifyErrors(true);
					throw new Exception();
				}
				
				answerJson = new JSONObject(answer);
    			if (answerJson.has("errors") && answerJson.getString("errors").equals("no"))
    				feedbackInsertionOutcome.setGamifyErrors(false);
    			else
    				feedbackInsertionOutcome.setGamifyErrors(true);
			}
			
			response.getWriter().write(jsonManager.generateJSON(feedbackInsertionOutcome));
		} catch (Exception e1) {
			try {
				response.getWriter().write(jsonManager.generateJSON(feedbackInsertionOutcome));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
